from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from .models import OAuthQQUser
from .utils import QQOauth
from .exceptions import QQAPIException
from .serializers import QQAuthUserSerializer
from carts.utils import merge_cart_cookie_to_redis

import logging
# 日志记录器
logger = logging.getLogger('django')


class QQAuthURLView(APIView):

    def get(self,request):
        """

    # 提供用户用于登录到QQ服务器的二维码扫描界面网址
    # login_url = https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184
    # &redirect_uri=xx&state=next参数&scope=get_user_info
        :param request:
        :return:
        """

        # 获取用户的next参数
        next = request.query_params.get('next')

        oauth = QQOauth(state=next)
        login_url = oauth.get_login_url()
        # print(login_url)
        return Response({'login_url':login_url})


 # url(r'^qq/user/$', views.QQAuthUserView.as_view()), 

class QQAuthUserView(GenericAPIView):
    serializer_class = QQAuthUserSerializer


    def get(self, request):

        code = request.query_params.get('code')
        print(code)
        if code is None:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        oauth = QQOauth()
        try:
            access_token = oauth.get_access_token(code)
            print(access_token)
            open_id = oauth.get_openid(access_token)
            print(open_id)

        except QQAPIException as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)


        try:
            oauth_user = OAuthQQUser.objects.get(openid = open_id)

        except OAuthQQUser.DoesNotExist:

            # 如果openid没绑定美多商城用户，创建用户并绑定到openid
            # 需要对open_id进行签名计算，不让外界捕获到真实的open_id
            token = oauth.generate_save_user_token(open_id)

            # 将token响应给前端:access_token是自己将openid签名之后的key
            return Response({'access_token': token})
            # return Response({'open_id':open_id})

        #如果存在user，则进行返回jwt实现状态保持
        else:
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            # 使用当前的注册用户user生成载荷，该载荷内部会有{"username":"", "user_id":"", "email":""}
            user = oauth_user.user  # OAuthQQUser模型对象取出user
            payload = jwt_payload_handler(user)
            # JWT  token
            token = jwt_encode_handler(payload)

            response = Response({
                'username':user.username,
                'user_id':user.id,
                'token':token
            })

            response = merge_cart_cookie_to_redis(request=request,user=user,response=response)

            return response


    #绑定用户到openid
    def post(self,request):

        serializer = self.get_serializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)


        response = Response({
            'username': user.username,
            'user_id': user.id,
            'token': token
        })

        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response


